<?php

namespace App\Console\Commands;

use App\Models\AccountMapping;
use App\Models\Mall;
use App\Models\MallDateFinance;
use App\Models\ProjectMall;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ProjectMallEnd extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:project-mall-end';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $mallId = "1117469694874488832";
        $endTime = "2025-11-24";
        $reStartTime = "2025-11-24";
        $newMallId = $mallId."-1";
        DB::beginTransaction();
        try{

            $mall = Mall::query()->where("merchant_no",$mallId)->first();
            $name = $mall->name;
            $mall->merchant_no = $newMallId;
            $mall->name = $name."(已结束)";
            $mall->save();
            MallDateFinance::query()
                ->whereIn("merchant_no",[$mallId,$newMallId])
                ->where("date",">",$endTime)
                ->delete();
            MallDateFinance::query()
                ->where("merchant_no",$mallId)
                ->update(["merchant_no"=>$newMallId]);
            ProjectMall::query()
                ->whereIn("merchant_no",[$mallId,$newMallId])
                ->update(["end_back_date_time"=>$endTime]);
            $res = AccountMapping::query()
                ->whereIn("merchant_no",[$mallId,$newMallId])
                ->first();
            AccountMapping::query()
                ->whereIn("merchant_no",[$mallId,$newMallId])
                ->delete();
            $newMall = new Mall;
            $newMall->name = $name;
            $newMall->merchant_no = $mallId;
            $newMall->poi_id = $mall->poi_id;
            $newMall->sub_date = $reStartTime;
            $newMall->detail_sync_at = null;
            $newMall->sub_merchant_id = $mall->sub_merchant_id;
            $newMall->sub_merchant_date = $mall->sub_merchant_date;
            $newMall->counts_datas = $mall->counts_datas;
            $newMall->show_date = $reStartTime;
            $newMall->save();

            $newRel = new AccountMapping;
            $newRel->account_id = $res->account_id;
            $newRel->merchant_no = $mallId;
            $newRel->date_sync_at = $res->date_sync_at;
            $newRel->is_meituan_sync = $res->is_meituan_sync;
            $newRel->mall_type = $res->mall_type;
            $newRel->sub_merchant_type = $res->sub_merchant_type;
            $newRel->save();

            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            throw $e;
        }
    }
}
